import 'package:flutter/material.dart';
import 'package:flutter_taotaoshipin/http/dao/drama_dao.dart';
import 'package:flutter_taotaoshipin/model/drama_type_all_entity.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter_taotaoshipin/value/global_config.dart';
import 'package:get/get.dart';
import 'package:hi_net/core/hi_error.dart';

import 'category/drama_category_page.dart';
import 'drama_state.dart';

class DramaController extends GetxController
    with GetSingleTickerProviderStateMixin {
  var state = DramaState();

  late PageController pageController;

  @override
  void onInit() {
    super.onInit();
    _loadTypeAllData();
  }

  @override
  void onClose() {
    pageController.dispose();
    super.onClose();
  }

  ///切换tab
  void switchTap(int index) {
    state.selectedIndex = index;
    pageController.animateToPage(index,
        duration: Duration(milliseconds: 300), curve: Curves.ease);
  }

  void _addMore(List<DramaTypeAllEntity> types) {
    List<String> list = types.map((e) => e.name ?? '').toList();
    state.tabTitleList.add('全部');
    state.tabTitleList.addAll(list);
    // 初始化pagecontroller
    pageController =
        PageController(initialPage: state.selectedIndex);

    List<DramaCategoryPage> idList = [];
    for (DramaTypeAllEntity entity in types) {
      idList.add(DramaCategoryPage(categoryId: entity.id!));
    }
    state.pageList.add(DramaCategoryPage(
      categoryId: 0,
    ));
    state.pageList.addAll(idList);
  }

  Future<void> _loadTypeAllData() async {
    try {
      // 开始加载
      state.isLoading = true;
      update();

      var result = await DramaDao.getDramaTypeAll();
      if (result.code == 0) {
        // 成功
        if (result.data != null) {
          var types = result.data!;
          // 随机类别
          if (GlobalConfig.isReview == 1) {
            types.shuffle();
          }
          _addMore(types);
        } else {
          EasyLoading.showToast('数据为空');
        }
      } else {
        EasyLoading.showToast(result.message);
      }
    } on HiNetError catch (e) {
      EasyLoading.showToast(e.message);
    } catch (e) {
      EasyLoading.showToast(e.toString());
    }

    // 加载完成
    state.isLoading = false;
    update();
  }

  void onPageChanged(int value) {
    state.selectedIndex = value;
    update();
  }
}
